package com.google.project.client.Sharing;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.project.client.Admin.ADMEntrypoint;
import com.google.project.client.Director.DRTEntrypoint;
import com.google.project.client.HumanResources.HMEntrypoint;
import com.google.project.client.Operator.OPTEntrypoint;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DocumentDTO;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.UsersDTO;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.HTMLPanel;

public class MessageDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField
	VerticalPanel pWidget;
	@UiField
	Label lblSenderName;
	@UiField
	Label lblCreatedOnDate;
	@UiField
	Label lblSubject;
	@UiField
	TextArea taContent;
	@UiField
	Button btnReponse;
	@UiField
	TextArea taReponse;
	@UiField Button btnBack;
	@UiField HTMLPanel htmlPanel;
	@UiField Label lblAttach;

	interface Binder extends UiBinder<Widget, MessageDetail> {
	}

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final MessageServiceAsync messService = GWT
			.create(MessageService.class);
	List<MessageDTO> listMessage = new ArrayList<MessageDTO>();
	UsersDTO userDTO = new UsersDTO();
	MessageDTO ChildMessDTO = new MessageDTO();
	MessageDTO currMessDTO = new MessageDTO();
	private UploadServiceAsync rpc = GWT.create(UploadService.class);
	public MessageDetail() {
		initWidget(binder.createAndBindUi(this));
		// getMessByParentID();
	}
	public MessageDetail(MessageDTO _messDTO) {
		getInfoUserLogin() ;
		currMessDTO = _messDTO;
		getMessByParentID();
		getUrl(_messDTO.getId(),"4");
		initWidget(binder.createAndBindUi(this));
		
	}
	//get url link file
	public void getUrl(String forID,String dataType){
		rpc.getBlobs(forID, dataType, new AsyncCallback<List<DocumentDTO>>() {
			public void onSuccess(List<DocumentDTO> blobData) {
				if(blobData.size()>0){
					lblAttach.setVisible(true);
					htmlPanel.setVisible(true);
					String html = "<a target=\"_blank\" href=" + blobData.get(0).getUrl() + ">" + blobData.get(0).getDocumentName() + "</a>";
					SafeHtml safeHtml = SafeHtmlUtils.fromSafeConstant(html);
					 HTML na = new HTML(safeHtml);
					 htmlPanel.add(na);
				}
				
			}

			public void onFailure(Throwable caught) {
				Window.alert("couldn't get blob list, rpc failed");
			}
		});
	}
	// get info user login from session
	public void getInfoUserLogin() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(UsersDTO result) {
				userDTO = result;
				
			}
		});
	}

	// get all Message
	public void getMessByParentID() {
		messService.getMessageList(new AsyncCallback<List<MessageDTO>>() {

			@Override
			public void onSuccess(List<MessageDTO> result) {
				try {
					for (MessageDTO messageDTO : result) {
						listMessage.add(messageDTO);
					}

					List<MessageDTO> tempMess = new ArrayList<MessageDTO>();
					tempMess.clear();
					for (MessageDTO mess : listMessage) {
						if (mess.getParentId()!=null && mess.getParentId().equals(currMessDTO.getId())) {
							tempMess.add(mess);
						}
					}
					String top = "<div class=\"container\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					String top2 = "<div class=\"container2\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom2 = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					if (tempMess != null && tempMess.size() > 0) {
						int r = tempMess.size();
						int c = 1;
						Grid grid = new Grid(r, c);
						pWidget.add(grid);
						for (int i = 0; i < tempMess.size(); i++) {
							String senderName = tempMess.get(i).getSenderName();
							String content = tempMess.get(i).getContent();
							String createdOnDate = CommonFuntion
									.convertToDate(new Date(tempMess.get(i)
											.getCreatedOnDate()));
							grid.setWidget(i, 0, new HTML(top + "Người Gửi: "
									+ senderName + " <br> Ngày Gửi: "
									+ createdOnDate + "<br><br>" + top2
									+ content + bottom2 + bottom + "<br>"));
						}
					
					}
					// fill data to label
					lblSenderName.setText(currMessDTO.getSenderName());
					lblSubject.setText(currMessDTO.getSubject());
					taContent.setText(currMessDTO.getContent());
					lblCreatedOnDate.setText(CommonFuntion
							.convertToDate(new Date(currMessDTO
									.getCreatedOnDate())));
					Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
				        public void execute () {
				        	taReponse.setFocus(true);
				        }
				    });
					
				} catch (Exception ex) {
					ex.getMessage();
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	
	// get data to reponse
	public boolean getDataToReponse() {
		boolean flag = true;
		ChildMessDTO.setParentId(currMessDTO.getId());
		ChildMessDTO.setCreatedOnDate(new Date().getTime());
		ChildMessDTO.setProjectDTO(currMessDTO.getProjectDTO());
		ChildMessDTO.setProjectId(currMessDTO.getProjectId());
		//neu senderId cua mess cha = userId(login) 
		if(currMessDTO.getSenderId().equals(userDTO.getUserId())){
			ChildMessDTO.setReceiverId(currMessDTO.getReceiverId());
			ChildMessDTO.setReceiverName(currMessDTO.getReceiverName());
			ChildMessDTO.setSenderId(currMessDTO.getSenderId());
			ChildMessDTO.setSenderName(currMessDTO.getSenderName());
		}else{ 	//neu senderId cua mess cha # userId(login) 
			ChildMessDTO.setReceiverId(currMessDTO.getSenderId());
			ChildMessDTO.setReceiverName(currMessDTO.getSenderName());
			ChildMessDTO.setSenderId(currMessDTO.getReceiverId());
			ChildMessDTO.setSenderName(currMessDTO.getReceiverName());
		}
		ChildMessDTO.setTypeId(1);
		ChildMessDTO.setStatus(2); // nguoi gui chua doc
		ChildMessDTO.setSubject("Re:" + currMessDTO.getSubject());
		if (taReponse.getText().equalsIgnoreCase("")) {
			Window.alert("Bạn chưa nhập nội dung phản hồi!");
			flag = false;
		} else {
			ChildMessDTO.setContent(taReponse.getText());
		}
		return flag;
	}

	// click "gui phan hoi" ->add child mess + change status of mess's parent is
	// 2
	@UiHandler("btnReponse")
	void onBtnReponseClick(ClickEvent event) {
		if (getDataToReponse()) {

			messService.sendMessage(ChildMessDTO,
					new AsyncCallback<MessageDTO>() {

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Gửi tin nhắn thất bại!");

						}
						@Override
						public void onSuccess(MessageDTO result) {
							int status;
							//senderId cua mess cha=userid(login) thi khi phan hoi status=1
							if (currMessDTO.getSenderId().equals(
									userDTO.getUserId())) {
								status = 1;
							} 
							else {//senderId cua mess cha # userid(login) thi khi phan hoi status=2
								status = 2;
							}
							messService.updateParentMess(result.getParentId(),
									status, new AsyncCallback<Void>() {

										@Override
										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onSuccess(Void result) {
											Window
													.alert("Gửi tin nhắn thành công!");
											if(listMessage.size()>0){
												pWidget.clear();
												listMessage.clear();
												}
											getMessByParentID();
											taReponse.setText("");
											Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
										        public void execute () {
										        	taReponse.setFocus(true);
										        }
										    });
											
										}
									});

						}
					});
		}

	}

	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		if(userDTO.getUserGroup()==1){
			DRTEntrypoint.get().DRTMessList();
		}
		else if(userDTO.getUserGroup()==2){
			PMEntrypoint.get().PMMessageList();
		}else if(userDTO.getUserGroup()==3){
			OPTEntrypoint.get().OPTMessageList();
		}
		else if(userDTO.getUserGroup()==4){
			HMEntrypoint.get().HMMessList();
		}
		else if(userDTO.getUserGroup()==6){
			ADMEntrypoint.get().ADMMessList();
		}
	}
}
